<?php if (!defined("_ECRIRE_INC_VERSION")) return; if (class_exists('PdkRechercher')) return;
/**
 * SPIP Plugin Development Kit
 *
 * @author     Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 * @license    GNU/GPL
 * @package    plugins
 * @subpackage pdk
 * @category   outils
 * @copyright  (c) Aleksey Yaroshchuk 2011-2012
 * @link       http://www.spip-contrib.net/Developmet-Kit
 * @version    1.0.0
 */

include_spip('classes/pdk_model');
/** 
 *  This class is alternative for SPIP search engine
 *
 *  @author Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 */
class PdkRechercher {
    /**
     *  Recherche config array
     *  Format: array(
     *      'table_name1'=>array('field1','field2',...)
     *      'table_name2'=>array('field3','field4',...)
     *   );
     */
    public $recherche_fields = array(
        'articles'=>array('titre','texte','descriptif','chapo','surtitre','soustitre','ps'),
        'rubriques'=>array('titre','texte','descriptif'),
    );
    
    public function __construct() {
                
    }
    
    /**
     *  Create MySQL REGEXP pattern from string
     */
    public function CreateRegexp($recherche) {        
        $pattern = '/[\s+]+/';
        $recherche = preg_replace($pattern, '.*', $recherche);
        return $recherche; 
    }
    
    /**
     *  Create recherche from given code
     */
    public function CreateRecherche($recherche){
       $recherche = urldecode($recherche);
       include_spip('inc/filtres');
	   $recherche = corriger_caracteres($recherche);
       $recherche = unicode_to_utf_8(html2unicode(charset2unicode($recherche)));
       return $recherche; 
    }
    
    public function TableAllowed($id_table) {
        $tables = array_keys($this->recherche_fields); // Allowed tables
        return in_array($id_table, $tables);
    }
    
    /**
     *  Creates WHERE part of query wich will find $recherche pattern in $fields of $id_table table
     *  @param string $id_table ID of table in wich search for text
     *  @param string $pattern Pattern to search
     *  @param array $fields Array of fields in wich to search
     */
    public function CreateQuery($id_table, $pattern, $fields = array()) { //return false;
        $fields = $this->checkFields($fields, $id_table);
        $i = 1;
        $query = '';    
        foreach ($fields as $field) {
            $query .= "UPPER($field) REGEXP UPPER('$pattern')";
            if ($i!=count($fields))
                $query .= ' OR ';
            $i++;   
        }
        return $query;
    }
    
    /**
     *  Creates array wich can be added to $boucle->where array when creating criteria
     *  @param array $fields Fields in wich to search
     *  @param string $pattern Pattern to search
     */
    public function CreateBoucleWhereElement($id_table, $fields = array(), $pattern) {
        $fields = $this->checkFields($fields, $id_table);
        $right = "";        
        for ($i=1;$i<count($fields); $i++) {
            $right .= " OR UPPER(".$fields[$i].") REGEXP UPPER(\'$pattern\')";
        } 
        $right .= "'";
        return array("'REGEXP'", "'UPPER(".$fields[0].")'", "'UPPER(\'$pattern\')".$right);
    }
    
    private function checkFields($fields=array(), $id_table) {
        if (!$fields && isset($this->recherche_fields[$id_table]) && !empty($this->recherche_fields[$id_table]))
            $fields = $this->recherche_fields[$id_table];
        return $fields;        
    }
    
    /**
     *  Searches in database and returns found results
     *  @param string $recherche Text to find
     *  @param string $id_table ID of table in wich search for text
     *  @param array $fields Fields in which to search
     *  @param $where Additional where conditions (i.e. "statut='publie'")
     */
    public function GetSearchResults($recherche='', $id_table='articles', $fields=array(), $where=array()) {
        if (!$recherche) return array();
        $fields = $this->checkFields($fields, $id_table);
         
        $recherche = $this->CreateRecherche($recherche);
        $regexp = $this->CreateRegexp($recherche);
        $where[] = $this->CreateQuery($id_table, $regexp, $fields);
        
        //var_dump(sql_get_select('*','spip_articles',$where));
        // TODO: Optimization is needed. Only IDs must be selected
        return sql_fetch_all(sql_select('*','spip_'.$id_table, $where));
    }
    
    /**
     *  Searches in database and return found ids
     */
    public function GetSearchIDs($recherche='', $id_table='articles',$id_field='id_article', $fields=array(), $where=array()) {
        $results = $this->GetSearchResults(_request('recherche'), $id_table, $fields, $where);
        $ids = array();
        foreach ($results as $result) {
            $ids[] = $result[$id_field];
        }
        return $ids;
    }
}
?>